package com.fs.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.pojo.Class;
import com.fs.pojo.Course;
import com.fs.service.ClassService;
import com.fs.service.CourseService;
import com.fs.utils.BeanFactories;
import com.fs.utils.JsonData;
import com.fs.utils.ResponseJSONUtil;
import com.fs.vo.CourseClassVO;
import com.fs.vo.CourseVO;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.ColorUIResource;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "CourseSevlet", value = "/course/*")
public class CourseSevlet extends HttpServlet {
    private HttpServletRequest request;
    private HttpServletResponse response;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        this.request = request;
        this.response = response;

        if("/queryAllCourseByStudentId".equals(request.getPathInfo())){
            queryAllCourseByStudentId(null);
        }else if("/queryAllCourseByTeacherId".equals(request.getPathInfo())){
            queryAllCourseByTeacherId(null);
        }else if("/queryAllCourseByTeacherId".equals(request.getPathInfo())){
            addClassStudentByCourseCode();
        }else if("/deleteClassStudentByCourseId".equals(request.getPathInfo())){
            deleteClassStudentByCourseId();
        }else if("/isHaveCourseByCode".equals(request.getPathInfo())){
            isHaveCourseByCode();
        }else if("/queryCourseClassList".equals(request.getPathInfo())){
            queryCourseClassList(request,response);
        }else if("/createCourse".equals(request.getPathInfo())){
            createCourse(request,response);
        }else if("/delCourse".equals(request.getPathInfo())){
            delCourse(request,response);
        }else if("/updateCourse".equals(request.getPathInfo())){
            updateCourse(request,response);
        }
    }

    //查询所有课程班级列表班级
    private void queryCourseClassList(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

        CourseService courseService = BeanFactories.getBean(CourseService.class);
        String teacherId = request.getParameter("teacherId");
        List<CourseClassVO> list = courseService.queryCourseClassList(teacherId);

        JsonData jsonData = JsonData.buildSuccess(list);
        ResponseJSONUtil.responseJSON(jsonData,response);
    }

    /**
     * 创建课程
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    //创建课程
    private void createCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{


        CourseService courseService = BeanFactories.getBean(CourseService.class);

        String teacherId = request.getParameter("id");
        String imageUrl = request.getParameter("imageUrl");


        String courseName = request.getParameter("courseName");
        String courseDescription = request.getParameter("courseDescription");

        System.out.println("=============================================");
        System.out.println(imageUrl);

        Course course = new Course();
        course.setTeacherId(teacherId);
        course.setCourseName(courseName);
        course.setCourseDescription(courseDescription);
        course.setImg(imageUrl);

        Course c =  courseService.createCourse(course);
        if (c!=null) {
            ResponseJSONUtil.responseJSON(JsonData.buildSuccess(c), response);
        } else {
            ResponseJSONUtil.responseJSON(JsonData.buildError("error！"), response);
        }


    }


    /**
     * 修改课程
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void updateCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        CourseService courseService = BeanFactories.getBean(CourseService.class);
        String id = request.getParameter("id");
        String imageUrl = request.getParameter("imageUrl");
        String courseName = request.getParameter("courseName");
        String courseDescription = request.getParameter("courseDescription");
        Course course = new Course();
        course.setId(id);
        course.setImg(imageUrl);
        course.setCourseName(courseName);
        course.setCourseDescription(courseDescription);
        boolean b = courseService.updateCourse(course);

        if (b) {
            ResponseJSONUtil.responseJSON(JsonData.buildSuccess(b), response);
        } else {
            ResponseJSONUtil.responseJSON(JsonData.buildError("error！"), response);
        }


    }

    /**
     * 删除课程
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void delCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

        CourseService courseService = BeanFactories.getBean(CourseService.class);
        String courseId = request.getParameter("courseId");
        boolean b = courseService.delCourse(courseId);
        if (b) {
            ResponseJSONUtil.responseJSON(JsonData.buildSuccess(b), response);
        } else {
            ResponseJSONUtil.responseJSON(JsonData.buildError("error！"), response);
        }


    }


    /**
     * 根据用户ID查询所有
     * @param id 学生ID
     */
    private void queryAllCourseByStudentId(String id)throws ServletException, IOException {
        String  userID ;
        if(id == null){
            //获取前端传递的用户ID
            userID = request.getParameter("userID");
        }else {
            userID = id;
        }


        CourseService courseService = BeanFactories.getBean(CourseService.class);
        List<CourseVO> courses = courseService.queryAllCourseByStudentId(userID);
        JsonData data = JsonData.buildSuccess(courses);

        response.getWriter().println(JSONObject.toJSON(data));

    }


    /**
     * 根据教师ID查询所有
     * @param id 学生ID
     */
    private void queryAllCourseByTeacherId(String id)throws ServletException, IOException {
        String  userID ;
        if(id == null){
            //获取前端传递的用户ID
            userID = request.getParameter("userID");
        }else {
            userID = id;
        }

        CourseService courseService = BeanFactories.getBean(CourseService.class);
        List<CourseVO> courses = courseService.queryAllCourseByTeacherId(userID);
        JsonData data = JsonData.buildSuccess(courses);

        response.getWriter().println(JSONObject.toJSON(data));

    }


    /**
     * 根据课程暗号给对应用户添加课程
     * @throws ServletException
     * @throws IOException
     */
    private void addClassStudentByCourseCode()throws ServletException, IOException {
        JSONObject jsonObject = JSONObject.parseObject(IOUtils.toString(request.getInputStream(), "utf-8"));


        String courseCode = jsonObject.getString("courseCode");//前端传递的课程暗号
        String userID = jsonObject.getString("userID");//前端传递的用户id

        CourseService courseService = BeanFactories.getBean(CourseService.class);
        courseService.addClassStudentByCourseCode(courseCode,  userID);
        queryAllCourseByStudentId(userID);
    }


    /**
     * 根据课程名称删除课程学生记录
     */
    private void deleteClassStudentByCourseId()throws ServletException, IOException {
        //从流里获取数组
       // JSONArray jsonArray = JSONObject.parseArray(IOUtils.toString(request.getInputStream(), "utf-8"));

        JSONObject jsonObject = JSONObject.parseObject(IOUtils.toString(request.getInputStream(), "utf-8"));
        String studentId = jsonObject.getString("studentId");//前端传递的用户id

        JSONArray deleteIds = jsonObject.getJSONArray("deleteIds");

        CourseService courseService = BeanFactories.getBean(CourseService.class);
        courseService.deleteClassStudentByCourseName(deleteIds,studentId);//把获取的课程id

        queryAllCourseByStudentId(studentId);
    }

    //

    /**
     * 根据课程暗号查询是否有此课程
     * return （有此课程 返回 1 给前端，反之传 0）
     */
    private void isHaveCourseByCode()throws ServletException, IOException {

        //获取前端传过来的课程暗号
        String classCode = request.getParameter("classCode");

        CourseService courseService = BeanFactories.getBean(CourseService.class);
        int i = courseService.queryByCourseCode(classCode);

        JsonData json = JsonData.buildSuccess(i);

        response.getWriter().print(JSONObject.toJSONString(json));

    }
}
